/**
 * @author hanzc (hanzhichen@baijia.com)
 * @date 2021-01-25
 * fineBi经分概览看板part2: 流量收入转化看板
 */
import React, {useState, useEffect} from 'react';
import {useMount, useUpdateEffect} from 'ahooks';
import moment from 'moment';
import {Row, Col, Input, Card} from 'antd';
import {
    querySelectOptions,
    queryPart2Values,
    queryDetailInPart2,
    downloadInPart2
} from '~/service/generalView';
import CommonSearchBar from '../../../common/CommonSearchBar';
import {searchFormPart2, pageId} from '../../config';
import {convertChartListToMap, formatRangePickerValue} from '../../../utils/convert';
import DetailCard from '../../../common/DetailCard';
import DetailModal from '../../../common/DetailModal';
import Loading from '../../../common/Loading';
import GoalBarChart from './GoalBarChart';
import TrafficIncomeBarChart from './TrafficIncomeBarChart';
import TransformLineChart from './TransformLineChart';
import {META} from './config';

const {TextArea} = Input;

const initialValues = {};

const formatDateSearchValue = formatRangePickerValue('YYYY-MM-DD');

const TransformIncomeDashBoard = props => {
    // 第二部分报表使用第一部分报表的支付时间, 通过公共组件传递进来🥺
    const {originPaidDay} = props;

    const [loading, setLoading] = useState(false);
    const [result, setResult] = useState({});
    // searchform
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    // detail
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    const {generalViewPartSix = {}} = result;
    const {compositeUnit = [], textList = []} = generalViewPartSix;
    const textContent = textList?.[0]?.textContent ?? '';
    const chartMap = convertChartListToMap(compositeUnit);
    const {
        [META.CHART1]: chart1 = {},
        [META.CHART2]: chart2 = {},
        [META.CHART3]: chart3 = {}
    } = chartMap;

    const getData = (params = {}) => {
        setLoading(true);
        let newQueryParams = params;
        if (originPaidDay != null) {
            const formattedOriginPaidDay = formatDateSearchValue(originPaidDay);
            newQueryParams = {originPaidDay: formattedOriginPaidDay, ...params};
        }
        queryPart2Values(newQueryParams)
            .then(res => {
                const {data = {}} = res;
                setResult(data);
            })
            .finally(() => {
                setLoading(false);
            });
    };
    // searchform
    const handleSearch = params => {
        setSearchFormValues(params);
        getData(params);
    };
    const handleReset = () => {
        setSearchFormValues(initialValues);
        getData(initialValues);
    };
    // detail
    // 函数柯里化, 提前记录unit参数
    const handleDetail = ({unitId = '', unitName = ''}) => () => {
        setDetailModalVisible(true);
        let formattedSearchFormValues = searchFormValues;
        if (originPaidDay != null) {
            const formattedOriginPaidDay = formatDateSearchValue(originPaidDay);
            formattedSearchFormValues = {
                originPaidDay: formattedOriginPaidDay,
                ...searchFormValues
            };
        }
        const params = {
            ...formattedSearchFormValues,
            unitId,
            unitName
        };
        queryDetailInPart2(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };
    const handleDownload = ({unitId = '', unitName = ''}) => () => {
        let formattedSearchFormValues = searchFormValues;
        if (originPaidDay != null) {
            const formattedOriginPaidDay = formatDateSearchValue(originPaidDay);
            formattedSearchFormValues = {
                originPaidDay: formattedOriginPaidDay,
                ...searchFormValues
            };
        }
        const params = {
            ...formattedSearchFormValues,
            unitId,
            unitName
        };
        const excelName = unitName ? unitName : null;
        downloadInPart2({params, excelName});
    };
    // 请求单个表单配置项
    const handleFetchOptions = ({
        key,
        searchKey,
        pager,
        dependItemKey,
        dependItemValue,
        isGetingMore,
        options: curOptions,
        fieldsValue
    }) => {
        const permissions = searchFormPart2
            .map(item => ({
                dimensionId: item.key,
                dimensionName: item.key,
                filterItems: fieldsValue[item.key]
            }))
            .filter(item => item.filterItems?.length);
        const params = {
            pager,
            dimensionId: key,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: pageId.part2.selectID
        };
        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    // mount
    useMount(() => {
        getData(initialValues);
    }, []);

    // 当支付时间变化时, 重新查询数据
    useUpdateEffect(() => {
        getData(searchFormValues);
    }, [originPaidDay]);

    return (
        <div style={{marginTop: 24}}>
            <Card style={{marginBottom: 8}}>
                <Row>
                    <Col span={18}>
                        <CommonSearchBar
                            config={searchFormPart2}
                            selectOptions={selectOptions}
                            initialValues={initialValues}
                            noCache
                            onOk={handleSearch}
                            onReset={handleReset}
                            onfetchOptions={handleFetchOptions}
                            loading={loading}
                        />
                    </Col>
                    <Col span={6} style={{paddingLeft: 24}}>
                        <Loading loading={loading}>
                            <TextArea
                                value={textContent || ''}
                                readOnly
                                bordered={false}
                                className="general-text-area"
                                style={{height: 90}}
                            />
                        </Loading>
                    </Col>
                </Row>
            </Card>
            <Card>
                <Row>
                    <Col span={24}>
                        <DetailCard
                            title={chart1?.unitName ?? ''}
                            onDownload={handleDownload(chart1)}
                            onDetail={handleDetail(chart1)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <GoalBarChart dataSource={chart1} id="GoalChart" />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
                <Row>
                    <Col span={12}>
                        <DetailCard
                            title={chart2?.unitName ?? ''}
                            onDownload={handleDownload(chart2)}
                            onDetail={handleDetail(chart2)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <TrafficIncomeBarChart
                                    dataSource={chart2}
                                    id="TrafficIncomeChart"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                    <Col span={12}>
                        <DetailCard
                            title={chart3?.unitName ?? ''}
                            onDownload={handleDownload(chart3)}
                            onDetail={handleDetail(chart3)}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <TransformLineChart
                                    dataSource={chart3}
                                    id="TransformChart"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
            </Card>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
};

export default TransformIncomeDashBoard;
